package service

import (
	"api/app/ctl/models"
	"api/config"
	"api/libs/errs"
	"bufio"
	"fmt"
	"gitee.com/dreamwood/ez"
	"os/exec"
	"strings"
)

func Start(id int) error {
	crud := models.NewAppHostCrud()
	host, e := crud.Find(id)
	if errs.Try(e) {
		return e
	}
	go startHost(host)
	return nil
}

func Stop(id int) error {
	crud := models.NewAppHostCrud()
	host, _ := crud.Find(id)
	if host.IsLocal {
		return KillHost(id)
	}
	return nil
}

func startHost(host *models.AppHost) {
	cmds := strings.Fields(host.Params)

	cmd := exec.Command(host.Starter, cmds...)
	ez.Debug(cmd.String())
	stdout, e := cmd.StdoutPipe()
	stderr, e := cmd.StderrPipe()
	go func() {
		outReader := bufio.NewReader(stdout)
		for {
			line, _, e := outReader.ReadLine()
			if !errs.Try(e) {
				config.GetLogger().Printf("[]", string(line))
			}

		}
	}()
	go func() {
		errReader := bufio.NewReader(stderr)
		for {
			line, _, e := errReader.ReadLine()
			println(string(line))
			if e != nil {
				break
			}
		}
	}()
	e = cmd.Start()
	if e != nil {
		println("服务程序启动", e.Error())
	}
	ez.Debug("启动完成")
}

func AutoRun() {
	crud := models.NewAppHostCrud()
	//找到所有自启动的项目
	finds, e := crud.FindBy(ez.M{"isAutoRun": true}, nil, 0, 0)
	ez.PrintError(e)
	for _, find := range finds {
		e = Start(find.Id)
		ez.PrintError(e)
	}
}

func KillHost(appHostId int) (err error) {
	crud := models.NewAppHostCrud()
	host, err := crud.FindOneBy(ez.M{"id": appHostId}, nil)
	if err != nil {
		return
	}
	if !host.IsLocal {
		errs.Create("非本地项目")
		return
	}
	cmd := exec.Command("taskkill", "/F", "/PID", fmt.Sprintf("%d", host.Pid), "/T")
	err = cmd.Run()
	return
}

//todo kill gracefully
